package user

import (
	"time"

	"gitee.com/xgotool/backend-framework-template/config"
	"gitee.com/xgotool/backend-framework-template/model"
	"gitee.com/xgotool/backend-framework-template/service/captcha"
	"gitee.com/xgotool/backend-framework-template/service/users"
	"gitee.com/xiaoyutab/xgotool/individual/xginplus"
	"gitee.com/xiaoyutab/xgotool/individual/xqueue"
	"gitee.com/xiaoyutab/xgotool/xstring"
	"github.com/gin-gonic/gin"
)

// 用户登录的注册器方法
//
//	POST	/user/login
func Login(c *xginplus.Context) *xginplus.Response {
	type temp_struct struct {
		Captcha  string `json:"captcha" form:"captcha" xml:"captcha"`    // 验证码
		Id       string `json:"id" form:"id" xml:"id"`                   // 验证码id
		Username string `json:"username" form:"username" xml:"username"` // 登陆用户名
		Password string `json:"password" form:"password" xml:"password"` // 登陆密码
	}
	temp := temp_struct{}
	if err := c.Bind(&temp); err != nil {
		return c.Error(err)
	}
	type temp_struct_used struct {
		Captcha  string // 验证码
		Id       string // 验证码id
		Username string // 登陆用户名
		Password string // 登陆密码
	}
	param := temp_struct_used{}
	// 参数赋值
	param.Captcha = temp.Captcha
	param.Id = temp.Id
	param.Username = temp.Username
	param.Password = temp.Password
	// ApiPost软件所需要的参数描述格式:
	// [{"is_checked":1,"not_null":1,"key":"captcha","type":"Text","field_type":"String","value":"","description":"验证码"},{"is_checked":1,"not_null":1,"key":"id","type":"Text","field_type":"String","value":"","description":"验证码id"},{"is_checked":1,"not_null":1,"key":"username","type":"Text","field_type":"String","value":"","description":"登陆用户名"},{"is_checked":1,"not_null":1,"key":"password","type":"Text","field_type":"String","value":"","description":"登陆密码"}]
	// ApiFox软件所需要的参数描述格式:（此软件需要的参数为多行形式，请手动去除最前面的//和空格，再行复制）
	// "captcha","string","true","","","验证码"
	// "id","string","true","","","验证码id"
	// "username","string","true","","","登陆用户名"
	// "password","string","true","","","登陆密码"
	// 其他软件所需要的KV键值对描述:
	// {"captcha":"验证码","id":"验证码id","username":"登陆用户名","password":"登陆密码"}
	// 本命令执行参数【留做备份，以便后期使用/修改】
	// captcha string 验证码 v=required id string 验证码id v=required username string 登陆用户名 v=required password string 登陆密码 v=required x.ginplus
	// 参数效验部分
	if param.Captcha == "" {
		return c.Errorf("验证码(captcha) 不能为空")
	}
	if param.Id == "" {
		return c.Errorf("验证码id(id) 不能为空")
	}
	if param.Username == "" {
		return c.Errorf("登陆用户名(username) 不能为空")
	}
	if param.Password == "" {
		return c.Errorf("登陆密码(password) 不能为空")
	}

	// 验证验证码是否正确
	if !captcha.Verify(param.Id, param.Captcha) {
		xqueue.Set("log.user", &model.UserLog{
			Type: 1,
			Msg:  "用户 " + param.Username + " 验证码输入错误",
			Ip:   c.ClientIP(),
			Ua:   c.Request.UserAgent(),
			Time: time.Now().Unix(),
		})
		return c.Errorf("验证码错误，请校对后再次确认")
	}
	// 查询用户是否存在
	conn, err := config.GetConnect()
	if err != nil {
		return c.Error(err)
	}
	mod := model.User{}
	err = conn.Table(mod.TableName()).
		Where("user_name", param.Username).
		Where("status", 1).
		Order("id ASC").
		Find(&mod).
		Error
	if err != nil {
		return c.Error(err)
	}
	if mod.Id == 0 {
		xqueue.Set("log.user", &model.UserLog{
			Type: 1,
			Msg:  "用户 " + param.Username + " 用户名输入错误",
			Ip:   c.ClientIP(),
			Ua:   c.Request.UserAgent(),
			Time: time.Now().Unix(),
		})
		return c.Errorf("用户名或密码错误，请重新输入")
	}
	if !users.CheckPass(param.Password, mod.Password) {
		xqueue.Set("log.user", &model.UserLog{
			Type: 1,
			Uid:  mod.Id,
			Msg:  "用户 " + param.Username + " 密码输入错误",
			Ip:   c.ClientIP(),
			Ua:   c.Request.UserAgent(),
			Time: time.Now().Unix(),
		})
		return c.Errorf("用户名或密码错误，请重新输入")
	}
	// 登陆成功，设置session
	token, err := xstring.Jwt([]byte(config.GetExt().JWT.Key), gin.H{
		"id":       mod.Id,                                                   // 用户ID
		"username": mod.UserName,                                             // 用户名
		"sign":     xstring.MD5(mod.UserName + config.GetExt().JWT.Sign)[:6], // JWT效验，用于效验JWT是否被修改
		"iat":      time.Now().Unix(),                                        // 签发时间
	})
	if err != nil {
		return c.Error(err)
	}
	xqueue.Set("log.user", &model.UserLog{
		Type: 1,
		Uid:  mod.Id,
		Ip:   c.ClientIP(),
		Ua:   c.Request.UserAgent(),
		Time: time.Now().Unix(),
	})
	return c.Success(gin.H{
		"id":       mod.Id,       // 用户ID
		"username": mod.UserName, // 用户名
		"token":    token,        // JWT Token
	})
}
